﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Net.Http;
using Quail.Helpers;

namespace Quail
{
    /// <summary>
    /// Wraps a basic web request using a Query string and/or FormValues
    /// </summary>
    public class BasicWebRequest
    {
        // http://devatlapi:7050/json/User/AuthenticateUser?userName=john&password=test

        public BasicWebRequest(string baseUrl)
        {
            BaseUrl = baseUrl;
            Method = WebRequestMethods.Http.Get;
        }

        public BasicWebRequest()
        {
            Method = WebRequestMethods.Http.Get;
        }

        /// <summary>
        /// Gets the URI for the request
        /// </summary>
        /// <param name="defaultBaseUrl">The default base url to use if BaseUrl is NULL</param>
        public virtual Uri GetUri(string defaultBaseUrl = null)
        {
            Uri result;

            if (!Uri.TryCreate(Url, UriKind.RelativeOrAbsolute, out result) || !result.IsAbsoluteUri)
                result = new Uri((BaseUrl ?? defaultBaseUrl) + Url);

            var theurl = result.ToString();

            if (QueryString != null && QueryString.Count > 0)
            {
                if (!theurl.Contains("?"))
                    theurl += "?";
                else
                    theurl += "&";
                theurl += QueryString.ToQueryString();
            }

            return new Uri(theurl);
        }

        /// <summary>
        /// Gets the content to submit during the request
        /// </summary>
        /// <returns></returns>
        public virtual HttpContent GetContent()
        {
            if (FormValues.Count > 0)
            {
                // convert NameValueCollection to an IEnumerable<KeyValuePair<string,string>>
                return new FormUrlEncodedContent(FormValues.AllKeys.Select(k => new KeyValuePair<string, string>(k, FormValues[k])));
            }

            return new StringContent(string.Empty);
        }

        /// <summary>
        /// Gets or sets the relative URL for the request (/json/User/AuthenticateUser)
        /// </summary>
        public string Url { get; set; }

        /// <summary>
        /// Gets or sets the base URL for the request (http://www.example.com)
        /// </summary>
        public string BaseUrl
        { 
            get; set;
        }

        /// <summary>
        /// Gets or sets the method for the request (GET/POST/PUT/etc)
        /// </summary>
        public string Method { get; set; }

        /// <summary>
        /// Gets or sets a name value collection of query string parameters
        /// </summary>
        public NameValueCollection QueryString { get; set; } // { userName = john, password = test }

        /// <summary>
        /// Gets or sets a name value collection of form values
        /// </summary>
        public NameValueCollection FormValues { get; set; } // {}

        /// <summary>
        /// Logs this request to a task
        /// </summary>
        /// <param name="status"></param>
        /// <param name="task"></param>
        public virtual void Log(LogStatus status, Task task)
        {
            task.AddLog(status, string.Format("Url: {0}\nMethod: {1}\nElements: {2}",
                                              Url,
                                              Method,
                                              FormValues == null
                                                  ? string.Empty
                                                  : FormValues.ToQueryString()));
        }
    }
}
